package com.cynoware.busappmas.model;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
/**
 * 
 * @author This service is to capture screen shot and commit to server at an interval for real-time view
 *  Please call it by startService() and do not forget to stop it by stopService()
 */
public class ScreenCaptureService extends Service{
	
	private final String TAG = "ScreenCaptureService";
	private final int MSG_COMMIT_TO_SERVER = -1;
	private ContentResolver mContentResolver;
	private NetworkConnectChangedReceiver mReceiver;
	private Context mContext;
	private final int TIME_MS_CAPTURE_INTERVAL = 3000;//per 3 second
	private final String FILENAME_WITH_PATH = "/data/screen.png"; //filename of screen capture with absolute path, please change as you need
	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_COMMIT_TO_SERVER:
				captureInSubThread();
				mHandler.sendEmptyMessageDelayed(MSG_COMMIT_TO_SERVER, TIME_MS_CAPTURE_INTERVAL);
				break;
			}
		}
	};
	private class NetworkConnectChangedReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
	            NetworkInfo info = intent
	                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
	            if (info != null) {
	                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
	                    if (info.getType() == ConnectivityManager.TYPE_WIFI
	                            || info.getType() == ConnectivityManager.TYPE_MOBILE) {
	                        Log.i(TAG, "network connected!");
	                        mHandler.sendEmptyMessage(MSG_COMMIT_TO_SERVER);
	                    }
	                } else {
	                    Log.i(TAG, "network disconnected!");
	                }
	            }
	        }
		}
		
	};
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent,int flags,int startId){
		
		return super.onStartCommand(intent, flags, startId);
	}
	/**
	 *  Capture screen shot under FILENAME_WITH_PATH with subthread
	 *  NOTE: please do the job in subthread
	 */
	private synchronized void captureInSubThread(){
        new Thread(){
            @Override
            public void run(){
                Runtime runtime = Runtime.getRuntime();
                Process proc = null;
                OutputStream os = null;
                try {
                    proc = runtime.exec("ts");
                    os = proc.getOutputStream();
                    os.write(("screencap -p "+FILENAME_WITH_PATH+"\n").getBytes());//capture as png format
                    os.flush();
                    os.write("exit\n".getBytes());
                    os.flush();
                    proc.waitFor();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"root capture IO error!!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.e(TAG,"root capture intterupt!!");
                } finally{
                        try {
                            if(os != null)
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        proc.destroy();
                }
                

                
                Config cfg = Config.instance(mContentResolver);
                String url = "http://" + cfg.getServerIp().getValue() + ":" + cfg.getServerPort().getValue() + "/" + cfg.getSubServer().getValue();
                formUpload(url,FILENAME_WITH_PATH);
            }
            
        }.start();
    }	
	 /**
     * 
     * @param urlStr
     * @param filePath
     * @return
     */
    public String formUpload(String urlStr, String filePath) {
        String rsp = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "|"; 
        try {
            URL url = new URL(urlStr);
            Log.d(TAG,"url ="+urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            File file = new File(filePath);
            String filename = file.getName();
            String contentType = "";
            if (filename.endsWith(".png")) {
                contentType = "image/png";
            }
            if (filename.endsWith(".jpg")) {
                contentType = "image/jpg";
            }
            if (filename.endsWith(".gif")) {
                contentType = "image/gif";
            }
            if (filename.endsWith(".bmp")) {
                contentType = "image/bmp";
            }
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"" + filePath
                    + "\"; filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append("\n");
            }
            rsp = buffer.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return rsp;
    }
	@Override
	public void onCreate(){
		super.onCreate();
		mHandler.sendEmptyMessage(MSG_COMMIT_TO_SERVER);
		mContentResolver = this.getContentResolver();
        IntentFilter filter = new IntentFilter();
        //filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        //filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new NetworkConnectChangedReceiver();
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		mHandler.removeMessages(MSG_COMMIT_TO_SERVER);
	}

}
